package deployr.domain;

import static java.text.MessageFormat.*;

import java.io.*;
import java.util.*;

public class DiffSummary implements Serializable {

	private static final long serialVersionUID = -3264207270469966961L;

	private int added = 0;
	private int removed = 0;
	private int updated = 0;
	private String diff = "";

	public DiffSummary(final IUpdate update, final String diff) {
		this.diff = emptyIfNull(diff);
		parse();
	}

	private String emptyIfNull(String diff) {
		if (null == diff) return "";
		return diff;
	}

	public DiffSummary(final IUpdate update) {
		this(update, "");
	}

	public int addedCount() {
		return added;
	}

	public String content() {
		return diff;
	}

	private DiffCount countAdded() {
		return new DiffCount() {
			@Override
			public void andCount() {
				added++;
			}
		};
	}

	private DiffCount countRemoved() {
		return new DiffCount() {
			@Override
			public void andCount() {
				removed++;
			}
		};
	}

	private DiffCount countUpdated() {
		return new DiffCount() {
			@Override
			public void andCount() {
				updated++;
			}
		};
	}

	private boolean needContinue(final Scanner scanner) {
		return scanner.hasNext();
	}

	private void parse() {
		final Scanner scanning = scanning(diff);

		while (needContinue(scanning)) {
			final String nextDiff = scanning.next();

			recognizeAndCount(nextDiff);
		}
	}

	public DiffCount recognize(final String diff) {
		if (diff.startsWith("+")) return countAdded();
		if (diff.startsWith("-")) return countRemoved();
		if (diff.startsWith("*")) return countUpdated();
		return new DiffCount();
	}

	private void recognizeAndCount(final String diff) {
		recognize(diff).andCount();
	}

	public int removedCount() {
		return removed;
	}

	private Scanner scanning(final String string) {
		return new Scanner(string).useDelimiter("\n");
	}

	public String summary() {
		return format("{0} added, {1} updated, {2} removed", addedCount(), updatedCount(), removedCount());
	}

	public int updatedCount() {
		return updated;
	}
}
